import React, { useState, useEffect } from 'react';
import '../../style/kuangjia.css';
import '../../style/main.css';
import { useGlobalContext } from '../GlobalContext';

const RowSongList = ({ songList }) => {
  const {
    userId,
    favsongrefresh,
    setFavsongRefresh,
    playerlistfresh,
    setPlayerlistRefresh,
    currentIndex,
    setCurrentIndex,
    favsongListrefresh,
    setFavSonglistRefresh,
    playingDatalength,
    setPlayingDatalength,
  } = useGlobalContext();

  const itemsPerPage = 9; // 每页显示的项目数
  const [currentPage, setCurrentPage] = useState(0);
  const [songData, setSongData] = useState([]);

  // 计算总页数，每次 songData 更新时重新计算
  const totalPages = Math.ceil(songData.length / itemsPerPage);

  const getPlayUrl = async (id) => {
    try {
      const response = await fetch(`http://localhost:3000/song/url?id=${id}`);
      const data = await response.json();
      return data.data[0]?.url || '';
    } catch (error) {
      console.error('Error fetching song URL:', error);
      return '';
    }
  };

  const checkFavorStatus = async (songId) => {
    try {
      const response = await fetch(`http://localhost:8088/favor/${songId}`);
      const data = await response.json();
      return data.code === 200 && data.data !== null;
    } catch (error) {
      console.error('Error checking favor status:', error);
      return false; // 默认未收藏
    }
  };

  useEffect(() => {
    if (songList.length > 0) {
      const fetchSongData = async () => {
        const data = await Promise.all(
          songList.map(async (song, index) => {
            const playUrl = await getPlayUrl(song.id);
            const isFavorited = await checkFavorStatus(song.id);
            return {
              musicId: song.id,
              musicName: song.name,
              artName: song.ar[0]?.name || '未知',
              album: song.al.name,
              coverUrl: song.al.picUrl,
              lyricUrl: `http://localhost:3000/lyric?id=${song.id}`,
              dt: song.dt, // 持续时间（秒）
              playUrl,
              liked: isFavorited,
              songIndex: index,
              userId,
            };
          })
        );
        setSongData(data);
      };
      fetchSongData();
    }
  }, [songList, userId]);

  const handleNextPage = () => {
    if (currentPage < totalPages - 1) {
      setCurrentPage(currentPage + 1);
    }
  };

  const handlePreviousPage = () => {
    if (currentPage > 0) {
      setCurrentPage(currentPage - 1);
    }
  };

  const handleDeleteAll = async () => {
    try {
      const response = await fetch('http://localhost:8088/playing/deleteall', {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      });

      if (!response.ok) {
        throw new Error('Failed to delete all songs');
      }
      // setPlayerlistRefresh(!playerlistfresh);

    } catch (error) {
      console.error('Error deleting all songs:', error);
    }
    // setCurrentIndex(0)
  };

  const handleSongPlayClick = async (index) => {
    try {
      // 检查数据库是否存在数据
      const checkResponse = await fetch("http://localhost:8088/playing", {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      });
      const playingData = await checkResponse.json();
      if (playingData.data.length > 0) {
        // 如果存在数据，先清空播放列表
        await handleDeleteAll();
      }

      // 添加当前歌单到播放列表
      const response = await fetch("http://localhost:8088/playing/all", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(songData),
      });
      if (!response.ok) {
        throw new Error("Failed to update playing list");
      }

      // 设置全局变量和刷新状态
      setCurrentIndex(index);
      setPlayerlistRefresh(!playerlistfresh);
      console.log("Successfully added songs to the playing list");
    } catch (error) {
      console.error("Error handling song list update: ", error);
    }
  };

  const currentItems = songData.slice(currentPage * itemsPerPage, (currentPage + 1) * itemsPerPage);

  return (
    <div className="everybody_is_listening">
      <ul>
        <div
          className="hideicon4"
          onClick={handlePreviousPage}
          style={{ cursor: currentPage > 0 ? 'pointer' : 'not-allowed' }}
        >
          <i className="ri-arrow-left-wide-line"></i>
        </div>
        <div
          className="hideicon4"
          onClick={handleNextPage}
          style={{ cursor: currentPage < totalPages - 1 ? 'pointer' : 'not-allowed' }}
        >
          <i className="ri-arrow-right-wide-line"></i>
        </div>
        {currentItems.map((song, index) => (
          <li key={song.musicId || index}
            onClick={() => handleSongPlayClick(index)}
            className={currentIndex === index ? "playing" : ""}
          >

            {currentIndex === index ? (
              <div className='icon4'>
                <span className='playing2'></span>
              </div>) : (
              <div className="hideicon2">
                <i className="ri-play-fill"></i>
              </div>)}


            <div className="hideicon3">
              <i className="ri-heart-3-line"></i>
            </div>
            <div className="songImg">
              <img src={song.coverUrl} alt={song.album} />
            </div>
            <div className="song_name">
              <span id="songname">{song.musicName}</span>
              <span id="singer">{song.artName}</span>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default RowSongList;
